﻿using JWT.Handle;
using Newtonsoft.Json;
using Orm.Entities;
using Scm.Jwt.Dto;
using Scm.Orm.Helper;

namespace Scm.Jwt.Util
{
    public class JWTTokenUtil
    {

        /// <summary>
        /// 创建 token
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static AccessToken? GetToken(ScmUser user)
        {
            var UserDic = ObjectHandler.ObjectToDic(user);
            if (UserDic == null || UserDic.Count == 0) return null;
            var ExprieDateTime = DateTime.Now.AddMinutes(30);
            var AccessToken = new AccessToken
            {
                Token = JwtHandle.CreateJwtToken(UserDic),
                // token 过期时间
                Exprie = ExprieDateTime
            };
            CacheToken(AccessToken.Token, user, ExprieDateTime);
            return AccessToken;
        }

        /// <summary>
        /// 验证 token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static TokenCheckResult CheckToken(string token)
        {
            var Result = new TokenCheckResult();
            if (string.IsNullOrEmpty(token))
            {
                Result.Code = -1;
                Result.Msg = "token 为空";
                return Result;
            }
            string result = JwtHandle.ValidateJwtToken(token);
            switch (result)
            {
                case "expired":
                    Result.Code = -1;
                    Result.Msg = "token 已过期";
                    break;
                case "invalid":
                    Result.Code = -1;
                    Result.Msg = "token 验证无效";
                    break;
                case "error":
                    Result.Code = -1;
                    Result.Msg = "token 异常";
                    break;
                default:
                    Result.Code = 0;
                    Result.Msg = result;
                    break;
            }
            return Result;
        }

        /// <summary>
        /// 缓存token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        private static bool CacheToken(string token,ScmUser User,DateTime ExprieTime)
        {
            if (string.IsNullOrEmpty(token)) return false;
            var key = "Access_Token_" + StringUtil.MD5String(token);
            var value = JsonConvert.SerializeObject(User);
            RedisHelper.Save(key, value, ExprieTime - DateTime.Now);
            return true;
        }
    }

    public class TokenCheckResult
    {
        public int Code = 0;
        public string? Msg { get; set; }
    }

}
